package com.plugin.wxapp.serviceImpl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gitee.starblues.extension.mybatis.support.mybatisplus.ServiceImplWrapper;
import com.mybatisplus.main.common.DateUtils;
import com.mybatisplus.main.common.Result;
import com.plugin.wxapp.entity.MonsterUser;
import com.plugin.wxapp.entity.UserInfo;
import com.plugin.wxapp.mapper.MonsterUserMapper;
import com.plugin.wxapp.service.MonsterUserService;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
public class MonsterUserServiceImpl extends ServiceImplWrapper<MonsterUserMapper, MonsterUser> implements MonsterUserService {

    private OkHttpClient okHttpClient = new OkHttpClient();

    private String wxMiNiAppid = "wxf225f394c8b12af3";

    private String wxMiNiSecret = "53bccf322c407a80023b2e1e61c56e26";

    public MonsterUserServiceImpl(MonsterUserMapper baseMapper) {
        super(baseMapper);
    }

    @Override
    public Result login(UserInfo userInfo, Result<JSONObject> result) {
        if (StringUtils.isEmpty(userInfo.getCode())) {
            result.error500("未获取到code值");
            return result;
        }
        try {
            if(StringUtils.isNotEmpty(userInfo.getOpenid())) {
                QueryWrapper<MonsterUser> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("openid", userInfo.getOpenid());
                List<MonsterUser> list = baseMapper.selectList(queryWrapper);
                if (list != null && list.size() > 0) {
                    MonsterUser user = list.get(0);
                    if(StringUtils.isNotEmpty(userInfo.getNickName())) {
                        user.setNickname(userInfo.getNickName());
                    }
                    if(StringUtils.isNotEmpty(userInfo.getAvatarUrl())) {
                        user.setAvatarUrl(userInfo.getAvatarUrl());
                    }
                    user.setLastLogin(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
                    baseMapper.updateById(user);
                    result.success("登录成功");
                    return result;
                }
            }

            String body = okHttpClient.newCall(new Request.Builder()
                    .url("https://api.weixin.qq.com/sns/jscode2session?appid=" + wxMiNiAppid + "&secret=" + wxMiNiSecret +
                            "&grant_type=authorization_code&js_code=" + userInfo.getCode()).get().build()).execute().body().string();

            JSONObject jsonObject = JSONObject.parseObject(body);
            Integer errcode = jsonObject.getInteger("errcode");
            if (errcode == null || errcode == 0) {
                String miniOpenId = jsonObject.getString("openid");
                if (miniOpenId != null && miniOpenId != "") {
                    QueryWrapper<MonsterUser> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("openid", miniOpenId);
                    List<MonsterUser> list = baseMapper.selectList(queryWrapper);
                    if (list == null || list.size() <= 0) {
                        MonsterUser user = new MonsterUser();
                        if(StringUtils.isNotEmpty(userInfo.getNickName())) {
                            user.setNickname(userInfo.getNickName());
                        }
                        if(StringUtils.isNotEmpty(userInfo.getAvatarUrl())) {
                            user.setAvatarUrl(userInfo.getAvatarUrl());
                        }
                        user.setOpenid(miniOpenId);
                        user.setCreateTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
                        baseMapper.insert(user);
                    }
                    result.setResult(jsonObject);
                    result.success("登录成功");
                } else {
                    result.success("登录失败");
                }

            } else {
                result.success("访问失败");
            }
        } catch (IOException e) {
            throw new RuntimeException("微信访问异常");
        } catch (Exception e) {
            throw new RuntimeException("登录异常");
        }
        return result;
    }
}
